package com.example.springboot.controller;

import com.example.springboot.entity.Res;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/upload")
public class UploadController {
    private String uploadDirectory = "src/main/resources/static/image";

    @PostMapping("/image")
    public ResponseEntity<String> uploadImage(@RequestParam("image") MultipartFile image) {
        if (image.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("File is empty");
        }

        // 获取文件名并生成新的唯一文件名
        String originalFilename = StringUtils.cleanPath(image.getOriginalFilename());
        String fileExtension = StringUtils.getFilenameExtension(originalFilename);
//        String newFilename = UUID.randomUUID().toString() + "." + fileExtension;
        // 使用时间戳生成新的文件名
        String newFilename = System.currentTimeMillis() + "." + fileExtension;
        // 构建文件路径
        Path imagePath = Paths.get(uploadDirectory, newFilename);

        try {
            // 创建目录（如果不存在）
            Files.createDirectories(imagePath.getParent());

            // 保存文件
            Files.write(imagePath, image.getBytes());

            // 返回图片的 URL
            String imageUrl = newFilename;
            return ResponseEntity.ok(imageUrl);

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to save image");
        }
    }
    @DeleteMapping("/image/{url}")
    public Res<String> deleteImage(@PathVariable String url) {
        // 获取文件名并生成新的唯一文件名
        String fileName = StringUtils.cleanPath(url);
        // 构建文件路径
        Path imagePath = Paths.get(uploadDirectory, fileName);
        System.out.println(imagePath);
        try {
            // 删除文件
            Files.delete(imagePath);
            return new Res().code(200).msg("删除成功");
        } catch (IOException e) {
            e.printStackTrace();
            return new Res().code(500).msg("删除失败");
        }
    }

}
